#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
多模型系统测试脚本
测试OpenAI、DeepSeek和本地备用方案
"""

import sys
import time
from main import KnowledgeExplanationAgent
from model_status import model_status

def test_model_system():
    """测试多模型系统"""
    print("🤖 多模型系统测试")
    print("=" * 50)
    
    # 初始化智能体
    agent = KnowledgeExplanationAgent()
    
    # 测试问题列表
    test_questions = [
        "你好",
        "Rust的所有权是什么？",
        "如何使用迭代器？",
        "这个编译错误怎么解决？",
        "Rust和C++有什么区别？"
    ]
    
    for i, question in enumerate(test_questions, 1):
        print(f"\n📝 测试 {i}: {question}")
        print("-" * 30)
        
        try:
            # 处理问题
            result = agent.process_question("test_user", question)
            
            if result['status'] == 'success':
                print(f"✅ 处理成功")
                print(f"📊 问题类型: {result['classification']['label']}")
                print(f"🎯 置信度: {result['classification']['confidence']:.2f}")
                print(f"📝 回答长度: {len(result['answer_markdown'])} 字符")
                print(f"🔧 当前模型状态: {model_status.get_current_model()}")
                
                # 显示回答的前100个字符
                answer_preview = result['answer_markdown'][:100] + "..." if len(result['answer_markdown']) > 100 else result['answer_markdown']
                print(f"💬 回答预览: {answer_preview}")
            else:
                print(f"❌ 处理失败: {result['message']}")
                
        except Exception as e:
            print(f"❌ 异常: {e}")
        
        # 显示模型状态
        status = model_status.get_status_summary()
        print(f"\n📊 模型状态:")
        for model, info in status['status'].items():
            status_icon = "✅" if info['available'] else "❌"
            print(f"  {status_icon} {model}: {info['model']} (错误次数: {info['error_count']})")
        
        time.sleep(1)  # 避免API限制
    
    print(f"\n🎉 测试完成!")
    print(f"📈 最终模型状态: {model_status.get_status_summary()}")

def test_model_fallback():
    """测试模型故障转移"""
    print("\n🔄 测试模型故障转移")
    print("=" * 50)
    
    # 模拟OpenAI和DeepSeek都不可用的情况
    model_status.status['openai']['available'] = False
    model_status.status['deepseek']['available'] = False
    
    agent = KnowledgeExplanationAgent()
    
    test_question = "Rust的生命周期是什么？"
    print(f"📝 测试问题: {test_question}")
    
    try:
        result = agent.process_question("test_user", test_question)
        
        if result['status'] == 'success':
            print(f"✅ 本地备用方案工作正常")
            print(f"📊 问题类型: {result['classification']['label']}")
            print(f"💬 回答长度: {len(result['answer_markdown'])} 字符")
        else:
            print(f"❌ 备用方案失败: {result['message']}")
            
    except Exception as e:
        print(f"❌ 异常: {e}")
    
    # 恢复模型状态
    model_status.reset_status()

if __name__ == "__main__":
    print("🚀 启动多模型系统测试...")
    
    try:
        test_model_system()
        test_model_fallback()
        
        print("\n✅ 所有测试完成!")
        
    except KeyboardInterrupt:
        print("\n⏹️ 测试被用户中断")
    except Exception as e:
        print(f"\n❌ 测试过程中出现错误: {e}")
        sys.exit(1) 